package com.niit.search.controller;

import com.niit.chat.common.Result;
import com.niit.search.entity.SearchHistory;
import com.niit.search.entity.Topic;
import com.niit.search.service.SearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/search/history")
public class SearchHistoryController {

    @Autowired
    private SearchHistoryService searchHistoryService;

    @PostMapping
    public Result<?> saveSearchHistory(@RequestParam String keyword, @RequestParam(required = false) String userId) {
        Long userIdLong = userId != null && !userId.equals("null") ? Long.parseLong(userId) : null;
        searchHistoryService.saveHistory(userIdLong, keyword);
        return Result.success(null);
    }

    @GetMapping
    public Result<?> getSearchHistory(@RequestParam(required = false) String userId) {
        Long userIdLong = userId != null && !userId.equals("null") ? Long.parseLong(userId) : null;
        List<SearchHistory> history = searchHistoryService.getHistory(userIdLong);
        return Result.success(history);
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteSearchHistoryById(@PathVariable Long id, @RequestParam(required = false) String userId) {
        Long userIdLong = userId != null && !userId.equals("null") ? Long.parseLong(userId) : null;
        boolean success = searchHistoryService.deleteHistoryById(userIdLong, id);
        return success ? Result.success(null) : Result.error("删除失败");
    }

    @DeleteMapping
    public Result<?> deleteSearchHistoryByKeyword(@RequestParam String keyword, @RequestParam(required = false) String userId) {
        Long userIdLong = userId != null && !userId.equals("null") ? Long.parseLong(userId) : null;
        boolean success = searchHistoryService.deleteHistoryByKeyword(userIdLong, keyword);
        return success ? Result.success(null) : Result.error("删除失败");
    }
    
    @GetMapping("/hot")
    public Result<?> getHotTopics() {
        List<Topic> hotTopics = searchHistoryService.getHotTopics();
        return Result.success(hotTopics);
    }
}